package com.pds.web.company.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pds.common.core.domain.entity.SysDept;
import com.pds.common.core.domain.entity.SysUser;
import com.pds.common.utils.DateUtils;
import com.pds.common.utils.SecurityUtils;
import com.pds.common.utils.StringUtils;
import com.pds.system.domain.FileUpload;
import com.pds.system.domain.SysUserRole;
import com.pds.system.mapper.*;
import com.pds.web.area.entity.Area;
import com.pds.web.area.mapper.AreaMapper;
import com.pds.web.company.domain.PdsCompanyContact;
import com.pds.web.company.domain.PdsCompanyDTO;
import com.pds.web.company.domain.PdsCompanyInfo;
import com.pds.web.company.mapper.PdsCompanyContactMapper;
import com.pds.web.company.mapper.PdsCompanyInfoMapper;
import com.pds.web.company.service.IPdsCompanyInfoService;
import com.pds.web.industry.entity.Industry;
import com.pds.web.industry.service.IndustryService;
import com.pds.web.testOrganizationInfo.domain.PdsTestOrganizationInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class PdsCompanyInfoServiceImpl extends ServiceImpl<PdsCompanyInfoMapper, PdsCompanyInfo> implements IPdsCompanyInfoService {

    @Resource
    private PdsCompanyInfoMapper pdsCompanyInfoMapper;
    @Resource
    private PdsCompanyContactMapper pdsCompanyContactMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysConfigMapper sysConfigMapper;
    @Resource
    private AreaMapper areaMapper;
    @Resource
    private FileUploadMapper fileUploadMapper;
    @Autowired
    IndustryService industryService;

    /**
     * 新增
     *
     * @param pdsCompanyInfo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public Boolean addInfo(PdsCompanyInfo pdsCompanyInfo) {
        String createBy = SecurityUtils.getLoginUser().getUser().getNickName();
        Date date = DateUtils.parseDate(DateUtils.getTime());

        /*
         预备：用一个新PdsCompanyInfo对象只接收新增所需的10个字段:
              companyName、socialCreditCode、contactName、contactPhone、
              province、city、county、township、detailedAddress、
              pollutionDischargePermitId
         */
        PdsCompanyInfo pdsCompanyInfo_insert = new PdsCompanyInfo();
        pdsCompanyInfo_insert.setCompanyName(pdsCompanyInfo.getCompanyName());
        pdsCompanyInfo_insert.setSocialCreditCode(pdsCompanyInfo.getSocialCreditCode());
        pdsCompanyInfo_insert.setContactName(pdsCompanyInfo.getContactName());
        pdsCompanyInfo_insert.setContactPhone(pdsCompanyInfo.getContactPhone());
        pdsCompanyInfo_insert.setProvince(pdsCompanyInfo.getProvince());
        pdsCompanyInfo_insert.setCity(pdsCompanyInfo.getCity());
        pdsCompanyInfo_insert.setCounty(pdsCompanyInfo.getCounty());
        pdsCompanyInfo_insert.setTownship(pdsCompanyInfo.getTownship());
        pdsCompanyInfo_insert.setDetailedAddress(pdsCompanyInfo.getDetailedAddress());
        pdsCompanyInfo_insert.setPollutionDischargePermitId(pdsCompanyInfo.getPollutionDischargePermitId());

        //容错：新增属性中联系人电话和企业名称在系统中不能重复
        if (sysUserMapper.selectUserByUserName(pdsCompanyInfo_insert.getContactPhone()) != null
                || sysDeptMapper.selectDeptByDeptName(pdsCompanyInfo_insert.getCompanyName()) != null) {
            return false;
        }

        //1.在pds_company_info表中添加数据
        pdsCompanyInfo_insert.setStatus("0"); // 企业状态（0正常 1停用）
        pdsCompanyInfo_insert.setCreateBy(createBy);
        pdsCompanyInfo_insert.setCreateTime(date);
        pdsCompanyInfoMapper.insert(pdsCompanyInfo_insert);

        //2.在sys_dept表添加数据
        SysDept dept = new SysDept();
        //查询一级部门信息:0环保局，1检测机构，2企业，3运维机构
        //防止修改部门名称，导致无法添加企业机构信息
        SysDept lastDept = sysDeptMapper.getLastDeptByType(2);
        Long parentId = lastDept.getDeptId();
        String ancestors = lastDept.getAncestors();
        String[] ids = ancestors.split(",");
        if(ids.length>=3){
            //是二级以上目录
            parentId = Long.valueOf(ids[2]);
            ancestors = ids[0]+","+ids[1]+","+ids[2];
        }else{
            //是一级目录
            ancestors = ancestors+","+lastDept.getDeptId();
        }
        dept.setParentId(parentId);
        dept.setAncestors(ancestors);
        dept.setDeptName(pdsCompanyInfo_insert.getCompanyName());
        dept.setOrderNum(lastDept.getOrderNum()+1);
        dept.setCreateBy(createBy);
        dept.setType(2);
        dept.setOrganizationId(pdsCompanyInfo_insert.getId());
        sysDeptMapper.insertDept(dept);

        //3.在sys_user表添加数据
        SysUser user = new SysUser();
        user.setDeptId(dept.getDeptId());
        user.setUserName(pdsCompanyInfo_insert.getContactPhone());
        user.setNickName(pdsCompanyInfo_insert.getContactName());
        user.setPhonenumber(pdsCompanyInfo_insert.getContactPhone());
        user.setSex("2"); //性别（0男 1女 2未知）
        String initPassword = sysConfigMapper.selectInitPassword();
        user.setPassword(SecurityUtils.encryptPassword(initPassword));
        user.setCreateBy(createBy);
        sysUserMapper.insertUser(user);

        //4.将dept_id, user_id更新至pds_company_info表
        pdsCompanyInfo_insert.setDeptId(dept.getDeptId());
        pdsCompanyInfo_insert.setUserId(user.getUserId());
        pdsCompanyInfoMapper.updateById(pdsCompanyInfo_insert);

        //5.在sys_user_role表中给账号分配角色
        Long roleId = sysRoleMapper.getCompanyRoleId();
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(user.getUserId());
        userRole.setRoleId(roleId);
        List<SysUserRole> userRoleList = new ArrayList<>();
        userRoleList.add(userRole);
        sysUserRoleMapper.batchUserRole(userRoleList);

        //6.在pds_company_contact表中添加数据
        PdsCompanyContact pdsCompanyContact = new PdsCompanyContact();
        pdsCompanyContact.setUserId(user.getUserId());
        pdsCompanyContact.setRoleIds(String.valueOf(roleId));
        pdsCompanyContact.setCompanyId(pdsCompanyInfo_insert.getId());
        pdsCompanyContact.setName(pdsCompanyInfo_insert.getContactName());
        pdsCompanyContact.setPhone(pdsCompanyInfo_insert.getContactPhone());
        pdsCompanyContact.setStatus("0");  //账号状态（0正常 1停用）
        pdsCompanyContact.setCreateBy(createBy);
        pdsCompanyContact.setCreateTime(date);
        pdsCompanyContactMapper.insert(pdsCompanyContact);

        return true;
    }

    /**
     * 更新 -- 系统管理员
     *
     * @param pdsCompanyInfo
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public Boolean updateInfoBySysAdmin(PdsCompanyInfo pdsCompanyInfo) {
        String updateBy = SecurityUtils.getLoginUser().getUser().getNickName();
        Date date = DateUtils.parseDate(DateUtils.getTime());

        /*
         预备：用一个新PdsCompanyInfo对象只接收系统管理员能够更改的9个字段：
              companyName、socialCreditCode、contactName、contactPhone、
              province、city、county、township、detailedAddress、
         */
        PdsCompanyInfo pdsCompanyInfo_sysAdmin = new PdsCompanyInfo();
        pdsCompanyInfo_sysAdmin.setCompanyName(pdsCompanyInfo.getCompanyName());
        pdsCompanyInfo_sysAdmin.setSocialCreditCode(pdsCompanyInfo.getSocialCreditCode());
        pdsCompanyInfo_sysAdmin.setContactName(pdsCompanyInfo.getContactName());
        pdsCompanyInfo_sysAdmin.setContactPhone(pdsCompanyInfo.getContactPhone());
        pdsCompanyInfo_sysAdmin.setProvince(pdsCompanyInfo.getProvince());
        pdsCompanyInfo_sysAdmin.setCity(pdsCompanyInfo.getCity());
        pdsCompanyInfo_sysAdmin.setCounty(pdsCompanyInfo.getCounty());
        pdsCompanyInfo_sysAdmin.setTownship(pdsCompanyInfo.getTownship());
        pdsCompanyInfo_sysAdmin.setDetailedAddress(pdsCompanyInfo.getDetailedAddress());

        //1.在pds_company_info表中更新数据
        pdsCompanyInfo_sysAdmin.setId(pdsCompanyInfo.getId());
        pdsCompanyInfo_sysAdmin.setUpdateBy(updateBy);
        pdsCompanyInfo_sysAdmin.setUpdateTime(date);
        pdsCompanyInfoMapper.updateById(pdsCompanyInfo_sysAdmin);

        //2.在sys_dept表中更新数据
        SysDept dept = new SysDept();
        Long deptId = pdsCompanyInfoMapper.getDeptIdById(pdsCompanyInfo.getId());
        dept.setDeptId(deptId);
        dept.setDeptName(pdsCompanyInfo_sysAdmin.getCompanyName());
        dept.setUpdateBy(updateBy);
        sysDeptMapper.updateDept(dept);

        //3.在sys_user表中更新数据
        SysUser user = new SysUser();
        Long userId = pdsCompanyInfoMapper.getUserIdById(pdsCompanyInfo.getId());
        user.setUserId(userId);
        user.setUserName(pdsCompanyInfo_sysAdmin.getContactPhone());
        user.setNickName(pdsCompanyInfo_sysAdmin.getContactName());
        user.setPhonenumber(pdsCompanyInfo_sysAdmin.getContactPhone());
        user.setUpdateBy(updateBy);
        sysUserMapper.updateUser(user);

        //4.在sys_user_role表中更新数据
        //删除原有角色
        sysUserRoleMapper.deleteUserRoleByUserId(userId);
        //重新分配管理员角色
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(sysRoleMapper.getCompanyRoleId());
        List<SysUserRole> userRoleList = new ArrayList<>();
        userRoleList.add(userRole);
        sysUserRoleMapper.batchUserRole(userRoleList);

        //5.在pds_company_contact表中更新数据
        PdsCompanyContact pdsCompanyContact = new PdsCompanyContact();
        pdsCompanyContact.setId(pdsCompanyContactMapper.getIdByCompanyId(pdsCompanyInfo.getId()));
        pdsCompanyContact.setRoleIds(String.valueOf(sysRoleMapper.getCompanyRoleId()));
        pdsCompanyContact.setName(pdsCompanyInfo_sysAdmin.getContactName());
        pdsCompanyContact.setPhone(pdsCompanyInfo_sysAdmin.getContactPhone());
        pdsCompanyContact.setUpdateBy(updateBy);
        pdsCompanyContact.setUpdateTime(date);
        pdsCompanyContactMapper.updateById(pdsCompanyContact);

        return true;
    }

    /**
     * 更新 -- 企业管理员
     *
     * @param pdsCompanyInfo
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public Boolean updateInfoByCompanyAdmin(PdsCompanyInfo pdsCompanyInfo) {
        String updateBy = SecurityUtils.getLoginUser().getUser().getNickName();
        Date date = DateUtils.parseDate(DateUtils.getTime());

        //登录的企业管理员的deptId
        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
        //企业联系人的userId
        Long userId = pdsCompanyInfoMapper.getUserIdByDeptId(deptId);

        //1.在pds_company_info表中更新数据
        Long id = pdsCompanyInfoMapper.getIdByDeptId(deptId);
        pdsCompanyInfo.setId(id);
        pdsCompanyInfo.setCompanyName(null);
        pdsCompanyInfo.setSocialCreditCode(null);
        pdsCompanyInfo.setUpdateBy(updateBy);
        pdsCompanyInfo.setUpdateTime(date);
        pdsCompanyInfoMapper.updateById(pdsCompanyInfo);

        //2.在sys_user表中更新数据
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setUserName(pdsCompanyInfo.getContactPhone());
        user.setNickName(pdsCompanyInfo.getContactName());
        user.setPhonenumber(pdsCompanyInfo.getContactPhone());
        user.setUpdateBy(updateBy);
        sysUserMapper.updateUser(user);

        //4.在sys_user_role表中更新数据
        //删除原有角色
        sysUserRoleMapper.deleteUserRoleByUserId(userId);
        //重新分配管理员角色
        Long companyAdminRoleId = sysRoleMapper.getCompanyRoleId();
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(companyAdminRoleId);
        List<SysUserRole> userRoleList = new ArrayList<>();
        userRoleList.add(userRole);
        sysUserRoleMapper.batchUserRole(userRoleList);

        //5.在pds_company_contact表中更新数据
        PdsCompanyContact pdsCompanyContact = new PdsCompanyContact();
        pdsCompanyContact.setId(pdsCompanyContactMapper.getIdByUserId(userId));
        pdsCompanyContact.setRoleIds(String.valueOf(companyAdminRoleId));
        pdsCompanyContact.setName(pdsCompanyInfo.getContactName());
        pdsCompanyContact.setPhone(pdsCompanyInfo.getContactPhone());
        pdsCompanyContact.setUpdateBy(updateBy);
        pdsCompanyContact.setUpdateTime(date);
        pdsCompanyContactMapper.updateById(pdsCompanyContact);

        return true;
    }

    /**
     * 查询企业列表
     *
     * @param pdsCompanyInfo
     * @return
     */
    @Override
    public List<PdsCompanyInfo> getCompanyList(PdsCompanyInfo pdsCompanyInfo) {
        List<PdsCompanyInfo> companyList = pdsCompanyInfoMapper.getCompanyList(pdsCompanyInfo);

        companyList.stream().forEach(company -> {
            //查询附件信息
            getFileInfo(company);
            //查询省市四级文字
            StringBuilder addressCode = new StringBuilder();
            addressCode.append(company.getProvince()).append(",")
                    .append(company.getCity()).append(",")
                    .append(company.getCounty()).append(",")
                    .append(company.getTownship());
            String addressText = areaMapper.selectAddressByCode(addressCode.toString());
            company.setAddressText(addressText);
        });
        return companyList;
    }

    /**
     * 查询企业详细信息
     *
     * @param id 企业ID
     * @return
     */
    @Override
    public PdsCompanyInfo getInfoById(Long id) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser.getDept().getType().intValue() == 2) {
            //企业只能查看自己的信息
            id = sysUser.getDept().getOrganizationId();
        }
        PdsCompanyInfo pdsCompanyInfo = pdsCompanyInfoMapper.getCompanyById(id);
        //查询附件信息
        getFileInfo(pdsCompanyInfo);
        //查询省市四级文字
        StringBuilder addressCode = new StringBuilder();
        addressCode.append(pdsCompanyInfo.getProvince()).append(",")
                .append(pdsCompanyInfo.getCity()).append(",")
                .append(pdsCompanyInfo.getCounty()).append(",")
                .append(pdsCompanyInfo.getTownship());
        String addressText = areaMapper.selectAddressByCode(addressCode.toString());
        pdsCompanyInfo.setAddressText(addressText);
        //查询行业
        if(StringUtils.isNotEmpty(pdsCompanyInfo.getIndustry())) {
            Industry industry = industryService.getIndustryById(pdsCompanyInfo.getIndustry());
            if (industry!=null){
                pdsCompanyInfo.setIndustryName(industry.getName());
            }
        }
        return pdsCompanyInfo;
    }


    /**
     * 禁用企业
     *
     * @param pdsCompanyDTO
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public Boolean disableInfo(PdsCompanyDTO pdsCompanyDTO) {
        Long userId = pdsCompanyInfoMapper.getUserIdById(pdsCompanyDTO.getId());

        String updateBy = SecurityUtils.getLoginUser().getUser().getNickName();
        Date date = DateUtils.parseDate(DateUtils.getTime());

        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setStatus(pdsCompanyDTO.getStatus());
        user.setUpdateBy(updateBy);
        user.setUpdateTime(date);

        return sysUserMapper.updateStatus(user) > 0;
    }

    /**
     * 禁用、启用企业
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Long id, String status) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        PdsCompanyInfo info = new PdsCompanyInfo();
        info.setId(id);
        info.setStatus(status);
        info.setUpdateBy(sysUser.getNickName());
        info.setUpdateTime(new Date());
        pdsCompanyInfoMapper.updateById(info);
        SysDept dept = new SysDept();
        dept.setOrganizationId(id);
        dept.setStatus(status);
        dept.setUpdateBy(sysUser.getNickName());
        dept.setType(2);//企业
        sysDeptMapper.updateDeptByOrganizationId(dept);
    }

    /**
     * 批量导入企业
     *
     * @param list 企业信息
     * @param map  排污许可证id，key为excel中行-列号
     */
    @Override
    public void batchInsert(List<PdsCompanyInfo> list, Map map) throws Exception {
        int row = 1;
        for (PdsCompanyInfo info : list) {
            try {
                //省市县转换为code
                Area province = areaMapper.selectAddressByName(info.getProvince(),null);
                if(province==null){
                    throw new Exception("第"+row+"行错误：省选择错误");
                }
                Area city = areaMapper.selectAddressByName(info.getCity(),province.getCode());
                if(city == null){
                    throw new Exception("第"+row+"行错误：市选择错误");
                }
                Area county = areaMapper.selectAddressByName(info.getCounty(),city.getCode());
                if(county==null){
                    throw new Exception("第"+row+"行错误：县区选择错误");
                }
                Area township = areaMapper.selectAddressByName(info.getTownship(),county.getCode());
                if(township==null) {
                    throw new Exception("第"+row+"行错误：乡镇/街道选择错误");
                }
                info.setProvince(province.getCode());
                info.setCity(city.getCode());
                info.setCounty(county.getCode());
                info.setTownship(township.getCode());
                //排污许可证图片在excel中第9列
                if(ObjectUtil.isEmpty(map.get(row + "-9"))){
                    throw new Exception("第"+row+"行错误：请插入排污许可证图片");
                }
                String pollutionDischargePermitId = String.valueOf(map.get(row + "-9"));
                info.setPollutionDischargePermitId(pollutionDischargePermitId);
                addInfo(info);
            } catch (Exception e) {
                throw new Exception("第"+row+"行错误："+e.getMessage());
            }
            row++;
        }
    }

    /**
     * 查询附件信息
     *
     * @param info
     */
    private void getFileInfo(PdsCompanyInfo info) {
        String fileIds = "";

        if (StringUtils.isNotEmpty(info.getPollutionDischargePermitId())) {
            fileIds += info.getPollutionDischargePermitId() + ",";
        }

        if (StringUtils.isNotEmpty(fileIds)) {
            fileIds = fileIds.substring(0, fileIds.length() - 1);
            List<FileUpload> fileUploads = fileUploadMapper.selectFileUploadListByIds(fileIds.split(","));

            FileUpload fileUpload = fileUploads.get(0);
            Map temp = new HashMap(3);
            temp.put("fileId", fileUpload.getAttachmentId());
            temp.put("fileName", fileUpload.getFileName());
            temp.put("fileUrl", fileUpload.getUrl());

            info.setPollutionDischargePermitFile(temp);
        }
    }
}

